package com.yupi.project.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yupi.project.common.ErrorCode;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.mapper.UserMapper;
import com.yupi.project.model.entity.User;
import com.yupi.project.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.yupi.project.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author asus
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-01-22 11:30:26
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {


    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StringUtils.isNotEmpty(userAccount) && userAccount.length() > 256){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",userPassword);
        User user = this.getOne(queryWrapper);
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"登陆失败");
        }
        request.setAttribute(USER_LOGIN_STATE,user);
        return user;
    }

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        if (StringUtils.isAnyBlank(userAccount) || StringUtils.isAnyBlank(userPassword) || StringUtils.isAnyBlank(checkPassword)){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(userPassword);
        user.setUserName("");
        user.setUserAvatar("");
        user.setUserRole("");
        this.save(user);
        return user.getId();
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        return false;
    }

    @Override
    public boolean isAdmin(HttpServletRequest request) {
        User loginUser = (User) request.getAttribute(USER_LOGIN_STATE);
        String userRole = loginUser.getUserRole();
        if (userRole.equals("admin")){
            return true;
        }
        return false;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        User loginUser = (User) request.getAttribute(USER_LOGIN_STATE);
        return loginUser;
    }
}




